package com.alibaba.csp.sentinel.dashboard.rule.nacos.rule;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConstants;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosPropertiesConfiguration;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 从Nacos配置中心动态获取降级规则
 */
@Service
public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> {

	private static Logger logger = LoggerFactory.getLogger(DegradeRuleNacosProvider.class);

	@Autowired
	private NacosPropertiesConfiguration nacosPropertiesConfiguration;

	@Autowired
	private ConfigService configService;

	@Autowired
	private Converter<String, List<DegradeRuleEntity>> converter;

	/**
	 * 从Nacos配置中心拉取规则配置文件，并转换成正确的规则格式
	 *
	 * @param appName 规则名/配置文件名
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<DegradeRuleEntity> getRules(String appName) throws Exception {
		String dataId = new StringBuffer(appName).append(NacosConstants.DEGRADE_DATA_ID_SUFFIX).toString();
		String rules = configService.getConfig(dataId, nacosPropertiesConfiguration.getGroupId(), 3000);
		logger.info("pull DegradeRule from Nacos Config:{}", JSON.parse(rules));
		if (StringUtil.isEmpty(rules)) {
			return new ArrayList<>();
		}
		return converter.convert(rules);
	}
}
